package com.app.studyroom;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.studyroom.adapter.ClassroomAdapter;
import com.app.studyroom.adapter.FloorAdapter;
import com.app.studyroom.adapter.RowAdapter;
import com.app.studyroom.api.ApiClient;
import com.app.studyroom.api.ApiService;
import com.app.studyroom.api.model.ssrSeat.PageSeatListRequest;
import com.app.studyroom.api.model.ssrSeat.PageSeatListResponse;
import com.app.studyroom.api.model.ssrSeat.SeatItem;
import com.app.studyroom.mapper.ClassroomInfoMapper;
import com.app.studyroom.mapper.SeatMapper;
import com.app.studyroom.model.Classroom;
import com.app.studyroom.model.ClassroomDeserializer;
import com.app.studyroom.model.LayoutElement;
import com.app.studyroom.model.OverlayFrameView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.InputStream;
import java.util.*;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ClassActivity extends BaseActivity {

    private RecyclerView classroomRecyclerView, rowsRecyclerView, floorRecyclerView;
    private TextView classroomName;
    private TextView classroomStats;
    private TextView tvBindSeatPlace;
    private LinearLayout layout_hide;
    private Map<String, String[]> floorClassroomMap = new HashMap<>();
    private ImageView backButton;
    private OverlayFrameView overlayFrameView;

    protected boolean enableReservation = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        long enterTime = System.currentTimeMillis();
        Log.d("PerfTest", "进入 onCreate: " + enterTime);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.classroom_seat_layout);
        Log.d("PerfTest", "setContentView 之后耗时: " + (System.currentTimeMillis() - enterTime) + "ms");

        enableReservation = getIntent().getBooleanExtra("enableReservation", false);
        classroomRecyclerView = findViewById(R.id.classroom_recycler_view);
        rowsRecyclerView = findViewById(R.id.rows_recycler_view);
        classroomName = findViewById(R.id.current_classroom_title);
        floorRecyclerView = findViewById(R.id.floor_recycler_view);
        classroomStats = findViewById(R.id.tv_classroom_stats);
        overlayFrameView = findViewById(R.id.overlay_frame_view);
        backButton = findViewById(R.id.back_button);
        tvBindSeatPlace = findViewById(R.id.tvBindSeatPlace);
        layout_hide = findViewById(R.id.layout_hide);
        if (!enableReservation) {
            layout_hide.setVisibility(View.GONE);
        }else{
            SharedPreferences sessionSp = getSharedPreferences("Session", MODE_PRIVATE);
            String bindSeatPlace = sessionSp.getString("bindSeatPlace", null);
            String bindSeatNum = sessionSp.getString("bindSeatNum", null);
            //绑定座位显示
            String seatDisplay;
            if (bindSeatPlace != null && !bindSeatPlace.trim().isEmpty() &&
                    bindSeatNum != null && !bindSeatNum.trim().isEmpty()) {
                seatDisplay = bindSeatPlace + "-" + bindSeatNum;
            } else {
                seatDisplay = "无";
            }
            tvBindSeatPlace.setText(seatDisplay);
        }


        initData();
        setupFloorRecyclerView();
        setupClassroomRecyclerView();
        backButton.setOnClickListener(v -> onBackPressed());
    }

    private void initData() {
        long start = System.currentTimeMillis();
        Log.d("PerfTest", "initData 开始");
        floorClassroomMap.clear();

        for (String areaId : ClassroomInfoMapper.getAreaIdList()) {
            String areaName = ClassroomInfoMapper.getName(areaId);
            List<String> classroomNames = new ArrayList<>();
            for (String classroomId : ClassroomInfoMapper.getClassroomIdList()) {
                String parentId = ClassroomInfoMapper.getParentAreaId(classroomId);
                if (areaId.equals(parentId)) {
                    classroomNames.add(ClassroomInfoMapper.getName(classroomId));
                }
            }
            floorClassroomMap.put(areaName, classroomNames.toArray(new String[0]));
            Log.d("FloorInit", "put: " + areaName + " -> " + classroomNames);
        }
        Log.d("PerfTest", "initData 耗时: " + (System.currentTimeMillis() - start) + "ms");
    }

    private void setupFloorRecyclerView() {
        String[] floors = floorClassroomMap.keySet().toArray(new String[0]);
        FloorAdapter floorAdapter = new FloorAdapter(floors, this);
        floorRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        floorRecyclerView.setAdapter(floorAdapter);
        floorAdapter.setOnItemClickListener(this::loadClassroomsForFloor);
    }

    private void setupClassroomRecyclerView() {
        if (floorClassroomMap.isEmpty()) {
            Toast.makeText(this, "教室数据为空", Toast.LENGTH_SHORT).show();
            return;
        }
        String defaultFloor = floorClassroomMap.keySet().iterator().next();
        String[] classrooms = floorClassroomMap.get(defaultFloor);
        if (classrooms == null || classrooms.length == 0) {
            Toast.makeText(this, "当前楼层下无教室", Toast.LENGTH_SHORT).show();
            return;
        }

        ClassroomAdapter classroomAdapter = new ClassroomAdapter(classrooms, this);
        classroomRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        classroomRecyclerView.setAdapter(classroomAdapter);
        classroomAdapter.setOnItemClickListener(this::loadClassroom);

        // 默认加载第一个教室
        loadClassroom(classrooms[0]);
    }

    private void loadClassroomsForFloor(String floor) {
        String[] classrooms = floorClassroomMap.get(floor);
        if (classrooms == null || classrooms.length == 0) {
            Toast.makeText(this, "该区域下无教室", Toast.LENGTH_SHORT).show();
            return;
        }
        ClassroomAdapter classroomAdapter = new ClassroomAdapter(classrooms, this);
        classroomRecyclerView.setAdapter(classroomAdapter);
        classroomAdapter.setOnItemClickListener(this::loadClassroom);
    }

    private void loadClassroom(String classroomNameStr) {

        long startLoad = System.currentTimeMillis();
        Log.d("PerfTest", "loadClassroom 开始加载: " + classroomNameStr);
//        String roomId = classroomNameStr.replace("教室", "");
        String roomId = classroomNameStr;  // ✅ 保留完整 "501教室"
        String filename = "classlayoutassets/layout_" + roomId + ".json";


        try {
            InputStream is = getAssets().open(filename);
            byte[] buffer = new byte[is.available()];
            is.read(buffer);
            is.close();

            String json = new String(buffer, "UTF-8");
            Gson gson = new GsonBuilder()
                    .registerTypeAdapter(Classroom.class, new ClassroomDeserializer())
                    .create();
            Classroom classroom = gson.fromJson(json, Classroom.class);

            if (classroom == null || classroom.getLayout() == null) {
                Toast.makeText(this, "教室布局加载失败", Toast.LENGTH_SHORT).show();
                return;
            }

            PageSeatListRequest request = new PageSeatListRequest(1, 1000);
            ApiService apiService = ApiClient.getClient().create(ApiService.class);
            Call<PageSeatListResponse> call = apiService.seatList(request);

            call.enqueue(new Callback<PageSeatListResponse>() {
                @Override
                public void onResponse(Call<PageSeatListResponse> call, Response<PageSeatListResponse> response) {
                    if (response.isSuccessful() && response.body() != null && response.body().getData() != null) {
                        List<SeatItem> allSeatList = response.body().getData().getData();

                        Map<String, String> seatStatusMap = new HashMap<>();
                        String backendRoomId = SeatMapper.getBackendRoom(roomId);
                        Log.d("SeatItemCheck", "roomId = " + roomId + ", backendRoomId = " + backendRoomId);

                        if (backendRoomId == null) {
                            Log.e("SeatItemCheck", "❌ backendRoomId is null！SeatMapper 可能未正确初始化 roomId=" + roomId);
                        } else {
                            for (SeatItem item : allSeatList) {
                                String seatPlace = item.getSeatPlace();
                                Log.d("SeatItemCheck", "seatPlace = " + seatPlace);

                                if (seatPlace != null && seatPlace.equals(backendRoomId)) {
                                    String key = seatPlace + "_" + item.getSeatNum();
                                    seatStatusMap.put(key, item.getSeatStatus());
                                    Log.d("SeatStatusMap", "✅ 匹配成功 key = " + key + ", 状态 = " + item.getSeatStatus());
                                }
                            }
                        }

                        // 设置布局中的 seatStatus
                        for (List<LayoutElement> row : classroom.getLayout()) {
                            for (LayoutElement elem : row) {
                                if (elem != null && "seat".equals(elem.type)) {
                                    String seatNum = SeatMapper.getBackendSeatNum(elem.id);
                                    String backendRoomIdInLoop = SeatMapper.getBackendRoom(roomId);  // 安全使用
                                    String key = backendRoomIdInLoop + "_" + seatNum;
                                    elem.seatStatus = seatStatusMap.getOrDefault(key, "0");
                                    Log.d("RenderSeat", "更新 seat[" + key + "] -> status=" + elem.seatStatus);
                                }
                            }
                        }

                        classroomName.setText(classroom.getName());
                        renderLayout(classroom.getLayout());
                        if (overlayFrameView != null) {
                            overlayFrameView.setFrameList(classroom.getFrames());
                        }
                        long responseTime = System.currentTimeMillis();
                        Log.d("PerfTest", "seatList 接口响应时间: " + (responseTime - startLoad) + "ms");

                    } else {
                        Toast.makeText(ClassActivity.this, "获取座位状态失败", Toast.LENGTH_SHORT).show();
                        classroomName.setText(classroom.getName());
                        renderLayout(classroom.getLayout());
                        if (overlayFrameView != null) {
                            overlayFrameView.setFrameList(classroom.getFrames());
                        }

                    }
                }

                @Override
                public void onFailure(Call<PageSeatListResponse> call, Throwable t) {
                    Toast.makeText(ClassActivity.this, "网络请求失败：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                    classroomName.setText(classroom.getName());
                    renderLayout(classroom.getLayout());
                    if (overlayFrameView != null) {
                        overlayFrameView.setFrameList(classroom.getFrames());
                    }

                }
            });

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "加载失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
        }
        Log.d("PerfTest", "loadClassroom 结束，总耗时: " + (System.currentTimeMillis() - startLoad) + "ms");
    }

    private void renderLayout(List<List<LayoutElement>> layoutRows) {
        long renderStart = System.currentTimeMillis();
        Log.d("PerfTest", "开始渲染 layout");        RowAdapter rowAdapter = new RowAdapter(layoutRows, enableReservation);
        rowsRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        rowsRecyclerView.setAdapter(rowAdapter);
        updateStats(layoutRows);
        Log.d("PerfTest", "renderLayout 渲染耗时: " + (System.currentTimeMillis() - renderStart) + "ms");
    }

    private void updateStats(List<List<LayoutElement>> layout) {
        int total = 0, reserved = 0, occupied = 0, maintenance = 0, applying = 0;

        for (List<LayoutElement> row : layout) {
            for (LayoutElement element : row) {
                if (element != null && "seat".equals(element.type)) {
                    total++;
                    String status = element.seatStatus;

                    if ("3".equals(status)) reserved++;
                    else if ("1".equals(status)) occupied++;
                    else if ("2".equals(status)) maintenance++;
                    else if ("4".equals(status)) applying++;
                }
            }
        }

        int percent = (total == 0) ? 0 : reserved * 100 / total;
        classroomStats.setText("已预约：" + reserved + "/" + total
                + "（占用率：" + percent + "%）  "
                + "占用：" + occupied + "  维护：" + maintenance + "  申请中：" + applying);
    }

    public void refreshStats() {
        loadClassroom(classroomName.getText().toString());
    }
}
